package com.ruoyi.system.mongo.Impl;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecuritySHA1Utils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.mongodb.*;
import com.ruoyi.system.mongo.StudentDao;
import org.apache.commons.codec.digest.DigestUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.regex.Pattern;

@Repository
public class StudentDaoImpl implements StudentDao {
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 根据用户id更改手机号进行认证
     */
    @Override
    public void updatePhoneNumById(Users user) {
        Query query=new Query(Criteria.where("id").is(user.getId()));
        Update update= new Update().set("phoneNum", user.getPhoneNum());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query,update,Users.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,TestEntity.class);
    }


    /**klasses班级表中根据学校得id 查询班级名称*/
    public List<Klasses> selectKlassesByClassName(String className) {
        Query query = new Query(Criteria.where("classname").is(className));
        List<Klasses> klassesList = mongoTemplate.find(query, Klasses.class);
        return klassesList;
    }

    /**klasses 根据班级id 查询*/
    @Override
    public Klasses selectKlassesById(String id) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(id)));
        Klasses klasse = mongoTemplate.findOne(query, Klasses.class);
        return klasse;
    }

    /**schools学校表中根据学校得id 查询学校名称*/
    public Schools selectSchoolsByNames(String schoolsName) {
        Query query = new Query(Criteria.where("names").is(schoolsName));
        Schools school = mongoTemplate.findOne(query, Schools.class);
        return school;
    }

    /**schools 根据学校id 查询*/
    @Override
    public Schools selectSchoolsById(Object id) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(id.toString())));
        Schools school = mongoTemplate.findOne(query, Schools.class);
        return school;
    }

    /**users学生表中根据学校得id 和  角色查询学校信息*/
    public PageInfo<Users> selectUsersBySchool(String schoolId,Integer role,Integer pageNum,Integer pageSize) {
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        if(pageNum != 0){
            pageNum = pageNum/pageSize;
        }
        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
        Query query = new Query(Criteria.where("school").is(new ObjectId(schoolId))
                .and("role").is(role));
        long total = mongoTemplate.count(query, Users.class,"users");
        List<Users> schoolsMGList = mongoTemplate.find(query.with(pageable), Users.class);
        PageInfo<Users> pageInfo = new PageInfo<>();
        pageInfo.setList(schoolsMGList); //结果集
        pageInfo.setTotal(total);  //总条数
        pageInfo.setPageNum(pageNum);//页码
        pageInfo.setPageSize(pageSize);//条数
        return pageInfo;
    }

    @Override
    public Users selectUsersByUserId(String UserId) {
        Query query = new Query(Criteria.where("id").is(UserId));
        Users user = mongoTemplate.findOne(query, Users.class);
        return user;
    }

    /**查询全部学生*/
    @Override
    public List<Users> selectUsersAlll() {
        return mongoTemplate.findAll(Users.class);
    }


    /**根据角色 查询*/
    @Override
    public PageInfo<Users> selectUsersByRole(Integer role,Integer pageNum,Integer pageSize) {
        Sort sort = Sort.by(Sort.Direction.ASC, "_id");
        if(pageNum != 0){
            pageNum = pageNum/pageSize;
        }
        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
        Query query = new Query(Criteria.where("role").is(role));
        long total = mongoTemplate.count(query, Users.class,"users");
        List<Users> usersList = mongoTemplate.find(query.with(pageable), Users.class,"users");
        PageInfo<Users> pageInfo = new PageInfo<>();
        pageInfo.setList(usersList); //结果集
        pageInfo.setTotal(total);  //总条数
        pageInfo.setPageNum(pageNum);//页码
        pageInfo.setPageSize(pageSize);//条数
        return pageInfo;
    }

    @Override
    public List<Works> selectWorksByUserId(String userId) {
        Query query = new Query(Criteria.where("user").is(new ObjectId(userId)));
        query.addCriteria(Criteria.where("isOnly").is(true));
        List<Works> works = mongoTemplate.find(query, Works.class);
        return works;
    }

    @Override
    public Unrels selectUnrelsById(String wordId) {
        Query query = new Query(Criteria.where("id").is(wordId));
        Unrels unrels = mongoTemplate.findOne(query, Unrels.class);
        return unrels;
    }

    @Override
    public Users findUserOpenid(String openid) {
        Query query=new Query(Criteria.where("openid").is(openid));
        Users user =  mongoTemplate.findOne(query , Users.class);
        return user;
    }

    @Override
    public String saveUser(Users users) {
        Users users1 = mongoTemplate.save(users);
        return users1.getId();
    }

    @Override
    public String saveUser1(Users users) {
        Users users1 = mongoTemplate.save(users);
        return users1.getId();
    }

    @Override
    public Users queryUsers(String username, String phoneNum) {
        Query query = new Query(Criteria.where("username").is(username));
        query.addCriteria(Criteria.where("phoneNum").is(phoneNum));
        Users users = mongoTemplate.findOne(query, Users.class);
        return users;
    }

    @Override
    public Users queryUsername(String username) {
        Query query = new Query(Criteria.where("username").is(username));
        Users users = mongoTemplate.findOne(query, Users.class);
        return users;
    }

    @Override
    public void updateUser(Users users) throws Exception {
        Query query = new Query();
        if (!StringUtils.isEmpty(users.getId())) {
            query.addCriteria(Criteria.where("_id").is(new ObjectId(users.getId())));
        }
        Update update = new Update();
        update.set("realname", users.getRealname()); //更新真实姓名
        update.set("sfz", users.getSfz()); //更新身份证
        update.set("email", users.getEmail()); //更新邮箱
        update.set("nikename", users.getNickname()); //更新昵称
        update.set("phoneNum", users.getPhoneNum());//更新常用电话
        update.set("school", users.getSchool());//所在学校
        update.set("schoolName", users.getSchoolName()); //所在学校名称
        mongoTemplate.upsert(query, update, Users.class);
    }

    @Override
    public void updatePassword(String username, String phoneNum, String email, String password) throws Exception {
        String passwords = SecuritySHA1Utils.shaEncode(password);
        Query query = new Query();
        if (!StringUtils.isEmpty(username)) {
            query.addCriteria(Criteria.where("username").is(username));
        }
        if (!StringUtils.isEmpty(phoneNum)) {
            query.addCriteria(Criteria.where("phoneNum").is(phoneNum));
        }
        if (!StringUtils.isEmpty(email)) {
            query.addCriteria(Criteria.where("email").is(email));
        }
        Update update = Update.update("password",passwords);
        mongoTemplate.updateFirst(query, update, Users.class);
    }

    @Override
    public void deleteWorksById(String id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, Works.class,"works");
    }

    public List<Users> selectUsersBySchool02(String SchoolId,Integer role) {

        Query query = new Query(Criteria.where("school").is(new ObjectId(SchoolId))
                .and("role").is(role));
        List<Users> schoolsMGList = mongoTemplate.find(query, Users.class);
        System.out.println("List>>>" + schoolsMGList);
        return schoolsMGList;
    }
    public List<Users> selectUsersByClassId(String classId,Integer role) {

        Query query = new Query(Criteria.where("classlist.klassid").is(new ObjectId(classId))
                .and("role").is(role));
        List<Users> userList = mongoTemplate.find(query, Users.class);
        System.out.println("List>>>" + userList);
        return userList;
    }
}
